package com.newear.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.newear.R;
import com.newear.happyDialog.WifiPasswordDialog;
import com.newear.util.T;
import com.newear.util.Validator;
import com.newear.util.WifiManagerUtil;

import java.util.ArrayList;
import java.util.List;

public class HappySettingActivity extends AppCompatActivity {
    private static final String TAG = "HappySettingActivity";
    private ListView lv_wife_list;
    private MyWifeAdapter mWifiAdapter;
    private ArrayList<ScanResult> mWifiList;
    private Context mContext;
    private Button btn_setting_update;
    private BroadcastReceiver broadcastReceiver;
    private BroadcastReceiver connectedReceiver;
    private WifiPasswordDialog mWifePassWordDialog;
    private LinearLayout lL_need_hide;
    private int type = WifiManagerUtil.WifiCipherType.WIFICIPHER_WPA;
    private ImageView ivClose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.happy_setting_activity);
        mContext = this;
        init();
        findViews();
        setListeners();
        initWifiListView();
        initWifi();
    }

    private void initWifi() {
        WifiManagerUtil.getInstance(this).search();
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent intent) {
                Log.e(TAG, "Wifi onReceive");
                final String action = intent.getAction();
                if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                    // wifi已成功扫描到可用wifi
                    List<ScanResult> scanResults = WifiManagerUtil.getInstance(mContext).getWifiManager().getScanResults();
                    if (scanResults != null) {
                        for (int i = 0; i < scanResults.size(); i++) {
                            ScanResult tempScanResult = scanResults.get(i);
                            Log.e(TAG, "tempScanResult name:" + tempScanResult.SSID);
                            if (tempScanResult != null && Validator.isEffective(tempScanResult.SSID)) {
                                boolean isExits = false;
                                for (int j = 0; j < mWifiList.size(); j++) {
                                    String wifiName = tempScanResult.SSID;
                                    if (mWifiList.get(j).SSID.equals(wifiName)) {
                                        isExits = true;
                                        break;
                                    }
                                }
                                if (!isExits) {
                                    mWifiList.add(tempScanResult);
                                }
                            }
                        }
                        mWifiAdapter.notifyDataSetChanged();
                    }
                }
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        if (connectedReceiver != null) {
            unregisterReceiver(connectedReceiver);
        }
    }

    private void init() {
        mWifiList = new ArrayList();
    }

    private void findViews() {
        lv_wife_list = (ListView) findViewById(R.id.lv_wife_list);
        btn_setting_update = (Button) findViewById(R.id.btn_setting_update);
        lL_need_hide = (LinearLayout) findViewById(R.id.lL_need_hide);
        ivClose = (ImageView) findViewById(R.id.img_setting_close);
    }

    private void setListeners() {
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HappySettingActivity.this.finish();
            }
        });

        lv_wife_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                WifiManagerUtil.getInstance(mContext).getWifiManager().disconnect();
                final ScanResult scanResult = mWifiList.get(position);

                if (position != 0) {
                    ScanResult tempScanResult = mWifiList.get(position);
                    mWifiList.remove(position);
                    mWifiList.add(0, tempScanResult);
                    mWifiAdapter.notifyDataSetChanged();
                }

                String capabilities = scanResult.capabilities;
                if (!TextUtils.isEmpty(capabilities)) {
                    if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                        type = WifiManagerUtil.WifiCipherType.WIFICIPHER_WPA;
                    } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
                        type = WifiManagerUtil.WifiCipherType.WIFICIPHER_WEP;
                    } else {
                        type = WifiManagerUtil.WifiCipherType.WIFICIPHER_NOPASS;
                    }
                }
                WifiConfiguration config = WifiManagerUtil.getInstance(mContext).isExsits(scanResult.SSID);

                if (config == null) {
                    if (type != WifiManagerUtil.WifiCipherType.WIFICIPHER_NOPASS) { // 需要密码
                        //弹出wife密码输入页面,并隐藏视图
                        //lL_need_hide.setVisibility(View.INVISIBLE);
                        //btn_setting_update.setVisibility(View.INVISIBLE);
                        mWifePassWordDialog = new WifiPasswordDialog(mContext, R.style.dialog, scanResult.SSID);
                        mWifePassWordDialog.show();
                        mWifePassWordDialog.setOnSureClickListener(new WifiPasswordDialog.OnSureClickListener() {
                            @Override
                            public void sureClickListener(String passwWord) {
                                mWifePassWordDialog.dismiss();
                                //显示之前的视图
                                //lL_need_hide.setVisibility(View.VISIBLE);
                                //btn_setting_update.setVisibility(View.VISIBLE);
                                WifiConfiguration tempConfig = WifiManagerUtil.getInstance(mContext).createWifiConfig(scanResult.SSID, passwWord, type);
                                if (tempConfig != null) {
                                    registerConnectedReceiver();
                                    WifiManagerUtil.getInstance(mContext).connect(tempConfig);
                                }
                            }
                        });
                    } else {
                        config = WifiManagerUtil.getInstance(mContext).createWifiConfig(scanResult.SSID, "", type);
                        if (config != null) {
                            registerConnectedReceiver();
                            WifiManagerUtil.getInstance(mContext).connect(config);
                        }
                    }
                } else {
                    registerConnectedReceiver();
                    WifiManagerUtil.getInstance(mContext).connect(config);
                }
            }
        });

        btn_setting_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                T.shortToast(mContext, "当前已经是最新版本");
            }
        });
    }

    /**
     * 注册连接成功的接受者
     */
    private void registerConnectedReceiver() {
        if (connectedReceiver == null) {
            connectedReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent == null) {
                        return;
                    }
                    String action = intent.getAction();
                    if (!Validator.isEffective(action)) {
                        return;
                    }
                    if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                        NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                        if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                            Log.e(TAG, "连接已断开");
                        } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                            final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                            if (wifiInfo == null) {
                                return;
                            }
                            String ssid = wifiInfo.getSSID().replace("\"", "");
                            Log.e(TAG, "已连接到网络:" + ssid);
                            ((TextView)lv_wife_list.getChildAt(0).findViewById(R.id.tv_desc)).setText("已连接到网络");
                            int index = 0;
                            for (int i = 0; i < mWifiList.size(); i++) {
                                if (mWifiList.get(i).SSID.equals(ssid)) {
                                    index = i;
                                }
                            }
                            if (index != 0) {
                                ScanResult tempScanResult = mWifiList.get(index);
                                mWifiList.remove(index);
                                mWifiList.add(0, tempScanResult);
                                mWifiAdapter.notifyDataSetChanged();
                            }
                        } else {
                            NetworkInfo.DetailedState state = info.getDetailedState();
                            if (state == state.CONNECTING) {
                                Log.e(TAG, "连接中...");
                                ((TextView)lv_wife_list.getChildAt(0).findViewById(R.id.tv_desc)).setText("连接中...");
                            } else if (state == state.AUTHENTICATING) {
                                Log.e(TAG, "正在验证身份信息...");
                                ((TextView)lv_wife_list.getChildAt(0).findViewById(R.id.tv_desc)).setText("正在验证身份信息...");
                            } else if (state == state.OBTAINING_IPADDR) {
                                Log.e(TAG, "正在获取IP地址...");
                                ((TextView)lv_wife_list.getChildAt(0).findViewById(R.id.tv_desc)).setText("正在获取IP地址...");
                            } else if (state == state.FAILED) {
                                Log.e(TAG, "连接失败...");
                            }
                        }
                    }
                }
            };
        }
        registerReceiver(connectedReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
    }

    private void initWifiListView() {
        mWifiAdapter = new MyWifeAdapter();
        lv_wife_list.setAdapter(mWifiAdapter);
    }

    class MyWifeAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mWifiList.size();
        }

        @Override
        public Object getItem(int position) {
            return mWifiList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            WifeListViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.setting_wifi_list, null);
                holder = new WifeListViewHolder();
                holder.tvWifeName = (TextView) convertView.findViewById(R.id.tv_setting_name);
                convertView.setTag(holder);
            } else {
                holder = (WifeListViewHolder) convertView.getTag();
            }
            holder.tvWifeName.setText(mWifiList.get(position).SSID);
            return convertView;
        }

        class WifeListViewHolder {
            TextView tvWifeName;
        }

    }

}
